package com.king.oa.util;

import java.util.ArrayList;
import java.util.List;

import com.king.oa.base.DaoSupport;
import com.king.oa.domain.PageBean;
import com.opensymphony.xwork2.ActionContext;

/**
 * 用于辅助拼接HQL语句
 * 
 * @author KingSir
 *
 */
public class QueryHelper {

	private String fromClause; // FROM 子句
	private String whereClause = ""; // WHERE 子句
	private String orderByClause = ""; // ORDER BY 子句
	
	private List<Object> parameters = new ArrayList<>(); // 参数列表
	
	/**
	 * 生成FROM子句
	 * 
	 * @param clazz
	 * @param alles 别名
	 */
	public QueryHelper(Class<?> clazz, String alles){
		fromClause = "FROM " + clazz.getSimpleName() + " " +alles;
		
	}
	
	/**
	 * 拼接WHERE子句
	 * 
	 * @param condition
	 * @param param
	 */
	public QueryHelper addCondition(String condition, Object... params){
		// 拼接
		if(whereClause.length() == 0){
			whereClause = " WHERE " + condition;
		}else{
			whereClause += " AND " + condition;
		}
		
		// 参数
		if(params != null){
			for(Object p : params){
				parameters.add(p);
			}
		}
		return this;
	}
	
	/**
	 * 拼接WHERE子句
	 * 
	 * @param append
	 * 			是否要执行拼接
	 * @param condition
	 * @param param
	 */
	public QueryHelper addCondition(boolean append, String condition, Object... params){
		if(append){
			addCondition(condition, params);
		}
		return this;
	}
	
	/**
	 * 拼接ORDER BY 子句
	 * 
	 * @param propertyName 
	 * 			参与排序的属性名
	 * @param asc
	 * 			true表示升序，false表示降序
	 */
	public QueryHelper addOrderByProperty(String propertyName, boolean asc){
		
		if(whereClause.length() == 0){
			throw new RuntimeException("必须在执行一次 addCondition() 添加WHERE子句后才能执行此方法!");
		}
		
		if( orderByClause.length() == 0){
			orderByClause = " ORDER BY " + propertyName + ( asc ? " ASC" : " DESC" );
		}else{
			orderByClause += ", " + propertyName + ( asc ? " ASC" : " DESC" );
		}
		return this;
	}

	/**
	 * 拼接ORDER BY 子句
	 * 
	 * @param append 是否拼接
	 * 
	 * @param propertyName 
	 * 			参与排序的属性名
	 * @param asc
	 * 			true表示升序，false表示降序
	 */
	public QueryHelper addOrderByProperty(boolean append, String propertyName, boolean asc){
		if(append){
			addOrderByProperty(propertyName, asc);
		}
		return this;
	}
	
	/**
	 * 获取生成的用于查询数据列表的HQL语句
	 * @return
	 */
	public String getListQueryHql(){
		return fromClause + whereClause + orderByClause;
	}
	
	/**
	 * 获取生成的用于查询总记录数的HQL语句
	 * @return
	 */
	public String getCountQueryHql(){
		return "SELECT COUNT(*) " + fromClause + whereClause;
	}
	
	
	/**
	 * 获取HQL中参数值列表
	 * @return
	 */
	public List<Object> getParameters() {
		return parameters;
	}
	
	/**
	 * 查询分页信息，并放到值栈栈顶
	 * 
	 * @param service
	 * @param pageNum
	 * @param pageSize
	 */
	public void prepaerePageBean(DaoSupport<?> service, int pageNum, int pageSize){
		
		PageBean pageBean = service.findPageBean(pageNum, pageSize, this);
		ActionContext.getContext().getValueStack().push(pageBean);
		
	}
	
}
